use eframe::egui;
use image::{DynamicImage, GenericImageView};
use std::path::PathBuf;

fn main() -> Result<(), eframe::Error> {
    let options = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default()
            .with_inner_size([1200.0, 800.0])
            .with_min_inner_size([800.0, 600.0]),
        ..Default::default()
    };

    eframe::run_native(
        "图片切分工具",
        options,
        Box::new(|cc| {
            // 设置中文字体
            setup_chinese_fonts(&cc.egui_ctx);
            Ok(Box::new(ImageSplitterApp::default()))
        }),
    )
}

fn setup_chinese_fonts(ctx: &egui::Context) {
    let mut fonts = egui::FontDefinitions::default();

    // 尝试加载系统中文字体
    let font_paths = vec![
        "C:\\Windows\\Fonts\\msyh.ttc",      // 微软雅黑
        "C:\\Windows\\Fonts\\simhei.ttf",    // 黑体
        "C:\\Windows\\Fonts\\simsun.ttc",    // 宋体
    ];

    for font_path in font_paths {
        if let Ok(font_data) = std::fs::read(font_path) {
            fonts.font_data.insert(
                "chinese_font".to_owned(),
                egui::FontData::from_owned(font_data),
            );

            // 将字体设置为默认字体
            fonts
                .families
                .entry(egui::FontFamily::Proportional)
                .or_default()
                .insert(0, "chinese_font".to_owned());

            fonts
                .families
                .entry(egui::FontFamily::Monospace)
                .or_default()
                .push("chinese_font".to_owned());

            ctx.set_fonts(fonts);
            return;
        }
    }

    // 如果没有找到中文字体，使用默认字体（可能显示方框）
    println!("警告: 未找到中文字体，使用默认字体");
}

struct ImageSplitterApp {
    // 图片相关
    source_image: Option<DynamicImage>,
    source_path: Option<PathBuf>,
    image_texture: Option<egui::TextureHandle>,

    // 切分设置
    rows: u32,
    cols: u32,

    // 预览
    preview_tiles: Vec<egui::TextureHandle>,
    show_preview: bool,

    // 状态
    status_message: String,
}

impl Default for ImageSplitterApp {
    fn default() -> Self {
        Self {
            source_image: None,
            source_path: None,
            image_texture: None,
            rows: 2,
            cols: 2,
            preview_tiles: Vec::new(),
            show_preview: false,
            status_message: "请选择要切分的图片".to_string(),
        }
    }
}

impl eframe::App for ImageSplitterApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.heading("图片切分工具");
            ui.separator();

            // 控制面板
            ui.horizontal(|ui| {
                if ui.button("📁 选择图片").clicked() {
                    if let Some(path) = rfd::FileDialog::new()
                        .add_filter("图片文件", &["png", "jpg", "jpeg", "bmp", "gif"])
                        .pick_file()
                    {
                        self.load_image(path, ctx);
                    }
                }

                if self.source_image.is_some() {
                    ui.separator();
                    ui.label("行数:");
                    ui.add(egui::Slider::new(&mut self.rows, 1..=10));

                    ui.label("列数:");
                    ui.add(egui::Slider::new(&mut self.cols, 1..=10));

                    if ui.button("🔍 预览切分").clicked() {
                        self.generate_preview(ctx);
                    }

                    if self.show_preview {
                        if ui.button("💾 保存切分图片").clicked() {
                            if let Some(folder) = rfd::FileDialog::new().pick_folder() {
                                self.save_tiles(folder);
                            }
                        }
                    }
                }
            });

            ui.separator();

            // 状态信息
            ui.label(&self.status_message);
            ui.separator();

            // 显示内容
            egui::ScrollArea::both().show(ui, |ui| {
                if self.show_preview && !self.preview_tiles.is_empty() {
                    // 显示预览网格
                    self.show_preview_grid(ui);
                } else if let Some(texture) = &self.image_texture {
                    // 显示原始图片
                    ui.heading("原始图片:");
                    ui.image((texture.id(), texture.size_vec2() * 0.5));
                } else {
                    ui.vertical_centered(|ui| {
                        ui.add_space(100.0);
                        ui.heading("请选择一张图片开始");
                        ui.label("支持格式: PNG, JPG, BMP, GIF");
                    });
                }
            });
        });
    }
}

impl ImageSplitterApp {
    fn load_image(&mut self, path: PathBuf, ctx: &egui::Context) {
        match image::open(&path) {
            Ok(img) => {
                self.status_message = format!("已加载图片: {} ({}x{})",
                    path.file_name().unwrap().to_string_lossy(),
                    img.width(), img.height());

                // 创建纹理
                let rgba_image = img.to_rgba8();
                let size = [img.width() as _, img.height() as _];
                let pixels = rgba_image.as_flat_samples();

                let color_image = egui::ColorImage::from_rgba_unmultiplied(
                    size,
                    pixels.as_slice(),
                );

                let texture = ctx.load_texture(
                    "source_image",
                    color_image,
                    egui::TextureOptions::LINEAR,
                );

                self.source_image = Some(img);
                self.source_path = Some(path);
                self.image_texture = Some(texture);
                self.show_preview = false;
                self.preview_tiles.clear();
            }
            Err(e) => {
                self.status_message = format!("加载图片失败: {}", e);
            }
        }
    }

    fn generate_preview(&mut self, ctx: &egui::Context) {
        if let Some(img) = &self.source_image {
            self.preview_tiles.clear();

            let (width, height) = img.dimensions();
            let tile_width = width / self.cols;
            let tile_height = height / self.rows;

            self.status_message = format!(
                "切分预览: {}x{} = {} 块，每块 {}x{} 像素",
                self.rows, self.cols, self.rows * self.cols,
                tile_width, tile_height
            );

            for row in 0..self.rows {
                for col in 0..self.cols {
                    let x = col * tile_width;
                    let y = row * tile_height;

                    let tile = img.crop_imm(x, y, tile_width, tile_height);
                    let rgba_tile = tile.to_rgba8();

                    let size = [tile_width as _, tile_height as _];
                    let pixels = rgba_tile.as_flat_samples();

                    let color_image = egui::ColorImage::from_rgba_unmultiplied(
                        size,
                        pixels.as_slice(),
                    );

                    let texture = ctx.load_texture(
                        format!("tile_{}_{}", row, col),
                        color_image,
                        egui::TextureOptions::LINEAR,
                    );

                    self.preview_tiles.push(texture);
                }
            }

            self.show_preview = true;
        }
    }

    fn show_preview_grid(&self, ui: &mut egui::Ui) {
        ui.heading("切分预览:");
        ui.add_space(10.0);

        let tiles_per_row = self.cols as usize;
        let available_width = ui.available_width();
        let spacing = 10.0;
        let tile_display_size = ((available_width - spacing * (tiles_per_row as f32 + 1.0))
            / tiles_per_row as f32).min(200.0);

        for row in 0..self.rows as usize {
            ui.horizontal(|ui| {
                for col in 0..self.cols as usize {
                    let idx = row * tiles_per_row + col;
                    if let Some(texture) = self.preview_tiles.get(idx) {
                        ui.vertical(|ui| {
                            ui.image((texture.id(), egui::vec2(tile_display_size, tile_display_size)));
                            ui.label(format!("({}, {}) 第{}块", row, col, idx + 1));
                        });
                        ui.add_space(spacing);
                    }
                }
            });
            ui.add_space(spacing);
        }
    }

    fn save_tiles(&mut self, output_dir: PathBuf) {
        if let Some(img) = &self.source_image {
            let (width, height) = img.dimensions();
            let tile_width = width / self.cols;
            let tile_height = height / self.rows;

            let base_name = self.source_path
                .as_ref()
                .and_then(|p| p.file_stem())
                .and_then(|s| s.to_str())
                .unwrap_or("image");

            let extension = self.source_path
                .as_ref()
                .and_then(|p| p.extension())
                .and_then(|s| s.to_str())
                .unwrap_or("png");

            let mut count = 0;
            let mut saved = 0;

            for row in 0..self.rows {
                for col in 0..self.cols {
                    let x = col * tile_width;
                    let y = row * tile_height;

                    let tile = img.crop_imm(x, y, tile_width, tile_height);

                    let filename = format!("{}_{}_{}_{}.{}",
                        base_name, row, col, count + 1, extension);
                    let output_path = output_dir.join(&filename);

                    match tile.save(&output_path) {
                        Ok(_) => saved += 1,
                        Err(e) => {
                            self.status_message = format!("保存失败: {}", e);
                            return;
                        }
                    }
                    count += 1;
                }
            }

            self.status_message = format!(
                "成功保存 {} 块图片到: {}",
                saved,
                output_dir.display()
            );
        }
    }
}
